package com.heima.search.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.SearchArticleService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yunfei
 * @date 2022年10月23日 14:59
 */
@Service
public class SearchArticleServiceImpl implements SearchArticleService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public ResponseResult searchArticle(UserSearchDto searchDto) throws IOException {
        // 需要对参数做校验
        // searchWords: "黑马程序员", pageSize: 10
        if (ObjectUtil.isNull(searchDto)) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (StrUtil.isEmpty(searchDto.getSearchWords()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (searchDto.getPageSize() <= 0) searchDto.setPageSize(10);

        // 根据条件 查询ES
        // 举例:  搜索关键词是  黑马程序员
        // 需要在title中查询 还需要在content中查询  多字段查询
        // 查询指定条数 排序
        SearchRequest searchR = new SearchRequest("article_index");
        searchR.source().query(QueryBuilders.queryStringQuery(searchDto.getSearchWords())
                .field("title").field("content").defaultOperator(Operator.OR))
                .sort("publishTime", SortOrder.DESC)
                .size(searchDto.getPageSize())
                .highlighter(new HighlightBuilder()
                        .field("title").field("content")
                        .preTags("<font style='color: red; font-size: inherit;'>").postTags("</font>"));

        SearchResponse response = client.search(searchR, RequestOptions.DEFAULT);
        List<Map> vos = new ArrayList<>();
        for (SearchHit hit : response.getHits()) {
            String sourceStr = hit.getSourceAsString();
            Map map = JSONUtil.toBean(sourceStr, Map.class);
            // 替换title和content
            Map<String, HighlightField> fieldMap = hit.getHighlightFields();
            HighlightField title = fieldMap.get("title");
            if (ObjUtil.isNotEmpty(title)) {
                StringBuilder titleSB = new StringBuilder();
                for (Text fragment : title.fragments()) {
                    titleSB.append(fragment.toString());
                }
                map.put("h_title", titleSB.toString());
            }

            HighlightField content = fieldMap.get("content");
            if (ObjUtil.isNotEmpty(content)) {
                StringBuilder contentSB = new StringBuilder();
                for (Text fragment : content.fragments()) {
                    contentSB.append(fragment.toString());
                }
                map.put("h_content", contentSB.toString());
            }
            vos.add(map);
        }
        return ResponseResult.okResult(vos);
    }
}
